package com.winning.pmph.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.User;
import com.winning.pmph.mapper.RoleMapper;
import com.winning.pmph.mapper.UserMapper;
import com.winning.pmph.utils.LocalDateTimeUtil;
import com.winning.pmph.utils.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {
    @Resource
    RoleMapper roleMapper;
    @Resource
    UserMapper userMapper;

    public User getUserByUserName(String userName) {
        return lambdaQuery().eq(User::getUserName, userName).one();
    }

    public User getUserName(String name) {
        User user = lambdaQuery().eq(User::getName, name).one();
        return user;
    }

    public User login(String username, String password) {
        return lambdaQuery().eq(User::getUserName, username).eq(User::getPassword, password).one();
    }

    public int saveUser(User user) {
        if (StringUtils.isBlank(user.getId())) {
            List<User> users = lambdaQuery().eq(User::getUserName, user.getUserName()).list();
            if (users.size() > 0) {
                throw new RuntimeException("用户名重复,请重新输入");
            }
            if (user.getPassword() != null) {
                user.setPassword((MD5Utils.md5(user.getPassword())));
            } else {
                user.setPassword(MD5Utils.md5("Rwzs5978"));
            }
        }
        if (StringUtils.equals(user.getPassword(), "true")) {
            user.setPassword(MD5Utils.md5("Rwzs5978"));
        } else {
            user.setPassword(user.getPassword());
        }
        if (Objects.isNull(user.getStatus())) {
            user.setStatus(User.ENABLE);
        }
        if (user.getKind() == 1) {
            user.setKind(user.getKind());
        }
        user.setUpdatedTime(LocalDateTimeUtil.getNowAsString());
        saveOrUpdate(user);
        return 1;
    }

    public int deleteByUserId(String id) {
        int result = userMapper.deleteById(id);
        return result;
    }

    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    public User getUserById(String id) {
        User user = userMapper.selectById(id);
        return user;
    }
}
